package com.xyw.tearch_plugin

import android.app.Activity
import android.content.Context
import android.content.Context.WIFI_SERVICE
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat.startActivityForResult
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar


/** TearchPlugin */
class TearchPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {

    private lateinit var channel: MethodChannel

    private lateinit var mContext: Context

    private lateinit var mActivity: Activity


    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.flutterEngine.dartExecutor, "tearch_plugin")
        channel.setMethodCallHandler(this)
        mContext = flutterPluginBinding.applicationContext
    }

    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar) {
            val channel = MethodChannel(registrar.messenger(), "tearch_plugin")
            channel.setMethodCallHandler(TearchPlugin())
        }
    }


    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        /// 判断是否打开了位置信息
        if (call.method == "isOpen") {
            result.success(isOpen(mContext))
            return
        }

        if (call.method == "openGps") {
            result.success(openGps(mContext))
            return
        }


        ///获取WiFi mac address
        if (call.method == "getBssid") {
            result.success(getWiFiMacAddress())
            return
        }
        
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }


    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        Log.i("testttttt", "ActivityPluginBinding")
        mActivity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    }

    override fun onDetachedFromActivity() {
    }


    /**
     * 获取当前连接网络的ssid
     */
    private fun getWiFiMacAddress(): String? {
        print("getWiFiMacAddress")
        val wifiManager = mContext.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        print("wifiManager")
        return wifiManager.connectionInfo.bssid
    }

    fun goToMarket(context: Context, packageName: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = Uri.parse("market://details?id=${packageName}") //其中的com.lkk.travel是自己app的包名
        intent.flags = FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)
    }

    fun isOpen(context: Context): Boolean {
        var locationMode = 0
        val locationProviders: String
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            locationMode = try {
                Settings.Secure.getInt(context.contentResolver, Settings.Secure.LOCATION_MODE)
            } catch (e: Settings.SettingNotFoundException) {
                e.printStackTrace()
                return false
            }
            locationMode != Settings.Secure.LOCATION_MODE_OFF
        } else {
            locationProviders = Settings.Secure.getString(context.contentResolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED)
            !TextUtils.isEmpty(locationProviders)
        }

    }


    fun  openGps(context: Context):Boolean {
        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK)
//PermissionConstants.RC_GPS是请求码，可以在onActivityResult中根据该请求码判断用户是否已经在设置页面打开位置服务
//PermissionConstants.RC_GPS是请求码，可以在onActivityResult中根据该请求码判断用户是否已经在设置页面打开位置服务
        context.startActivity(intent)
        return  true
    }

}
